package com.salton123.imagepicker.ui;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.format.Formatter;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.CompoundButton;

import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.ViewPager;

import com.salton123.imagepciker.R;
import com.salton123.imagepicker.ImagePicker;
import com.salton123.imagepicker.bean.ImageItem;
import com.salton123.imagepicker.custom.ImagePickerTextRepository;
import com.salton123.imagepicker.log.ILog;
import com.salton123.imagepicker.util.NavigationBarChangeListener;
import com.salton123.imagepicker.util.Utils;
import com.salton123.imagepicker.view.SuperCheckBox;


/**
 * ================================================
 * 作    者：jeasonlzy（廖子尧 Github地址：https://github.com/jeasonlzy0216
 * 版    本：1.0
 * 创建日期：2016/5/19
 * 描    述：
 * 修订历史：
 * ================================================
 */
public class ImagePreviewActivity extends ImagePreviewBaseActivity implements
        ImagePicker.OnImageSelectedListener, View.OnClickListener, CompoundButton.OnCheckedChangeListener {
    private static final String TAG = "ImagePreviewActivity";

    public static final String ISORIGIN = "isOrigin";

    private boolean isOrigin;                      //是否选中原图
    private SuperCheckBox mCbCheck;                //是否选中当前图片的CheckBox
    private SuperCheckBox mCbOrigin;               //原图
    private View bottomBar;
    private View marginView;
    private String hasChoose;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        isOrigin = getIntent().getBooleanExtra(ImagePreviewActivity.ISORIGIN, false);
        bottomBar = findViewById(R.id.bottom_bar);
        mSelectCount.setVisibility(View.VISIBLE);
        mBtnOk.setVisibility(View.VISIBLE);
        mBtnOk.setOnClickListener(this);

        mCbCheck = (SuperCheckBox) findViewById(R.id.cb_check);
        mCbOrigin = (SuperCheckBox) findViewById(R.id.cb_origin);
        marginView = findViewById(R.id.margin_bottom);
        mCbOrigin.setText(getString(R.string.ip_origin));
        mCbOrigin.setOnCheckedChangeListener(this);
        mCbOrigin.setChecked(isOrigin);

        if (mImageItems == null || mImageItems.size() == 0) {
            ILog.e(TAG, "onCreate: mImageItems == null or empty");
            return;
        }
        ILog.i(TAG, "imagePicker: " + imagePicker);
        imagePicker.addOnImageSelectedListener(this);
        //初始化当前页面的状态
        onImageSelected(0, null, false);
        ImageItem item = mImageItems.get(mCurrentPosition);
        boolean isSelected = imagePicker.isSelect(item);
        mTitleCount.setText(getString(R.string.ip_preview_image_count, mCurrentPosition + 1, mImageItems.size()));
        mCbCheck.setChecked(isSelected);
        mCbCheck.setVisibility(View.VISIBLE);
        //滑动ViewPager的时候，根据外界的数据改变当前的选中状态和当前的图片的位置描述文本
        mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                mCurrentPosition = position;
                ImageItem item = mImageItems.get(mCurrentPosition);
                boolean isSelected = imagePicker.isSelect(item);
                mCbCheck.setChecked(isSelected);
                mTitleCount.setText(getString(R.string.ip_preview_image_count,
                        mCurrentPosition + 1, mImageItems.size()));
//                if (imagePicker.getSelectSizeLimitLower() > 0 && item.size < imagePicker.getSelectSizeLimitLower()) {
//                    sizeLimitView.setVisibility(View.VISIBLE);
//                } else {
//                    sizeLimitView.setVisibility(View.GONE);
//                }
            }
        });
        //当点击当前选中按钮的时候，需要根据当前的选中状态添加和移除图片
        mCbCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImageItem imageItem = mImageItems.get(mCurrentPosition);
                //数量限制
                int selectLimit = imagePicker.getSelectLimit();
                if (mCbCheck.isChecked() && selectedImages.size() >= selectLimit) {
                    if (imagePicker.getSelectAmountLimitCallback() != null) {
                        imagePicker.getSelectAmountLimitCallback().onLimitToast();
                    } else {
                        showToast(getString(R.string.ip_select_limit, selectLimit));
                    }
                    mCbCheck.setChecked(false);
                    return;
                }
                //视频大小限制
                if (mCbCheck.isChecked() && imageItem.mimeType.startsWith("video")
                        && imageItem.size > imagePicker.getVideoSelectSizeLimitUpper()) {
                    ILog.d(TAG, "onClick: videoItem.size > limit upper");
                    if (imagePicker.getVideoSelectSizeLimitCallback() != null) {
                        imagePicker.getVideoSelectSizeLimitCallback().onLimitToastUpper(imageItem);
                    }
                    mCbCheck.setChecked(false);
                    return;
                }
                //图片下限限制
                if (mCbCheck.isChecked() && imageItem.mimeType.startsWith("image")
                        && imageItem.size < imagePicker.getSelectSizeLimitLower()) {
                    ILog.d(TAG, "onClick: imageItem.size < limit lower");
                    if (imagePicker.getSelectSizeLimitCallback() != null) {
                        imagePicker.getSelectSizeLimitCallback().onLimitToastLower(imageItem);
                    }
                    mCbCheck.setChecked(false);
                    return;
                }
                //图片上限限制
                if (mCbCheck.isChecked() && imageItem.mimeType.startsWith("image")
                        && imageItem.size > imagePicker.getSelectSizeLimitUpper()) {
                    ILog.d(TAG, "onClick: imageItem.size > limit upper");
                    if (imagePicker.getSelectSizeLimitCallback() != null) {
                        imagePicker.getSelectSizeLimitCallback().onLimitToastUpper(imageItem);
                    }
                    mCbCheck.setChecked(false);
                    return;
                }
                //正常入队
                imagePicker.addSelectedImageItem(mCurrentPosition, imageItem, mCbCheck.isChecked());
            }
        });
        NavigationBarChangeListener.with(this).setListener(
                new NavigationBarChangeListener.OnSoftInputStateChangeListener() {
                    @Override
                    public void onNavigationBarShow(int orientation, int height) {
                        marginView.setVisibility(View.VISIBLE);
                        ViewGroup.LayoutParams layoutParams = marginView.getLayoutParams();
                        if (layoutParams.height == 0) {
                            layoutParams.height = Utils.getNavigationBarHeight(ImagePreviewActivity.this);
                            marginView.requestLayout();
                        }
                    }

                    @Override
                    public void onNavigationBarHide(int orientation) {
                        marginView.setVisibility(View.GONE);
                    }
                });
        NavigationBarChangeListener.with(this, NavigationBarChangeListener.ORIENTATION_HORIZONTAL)
                .setListener(new NavigationBarChangeListener.OnSoftInputStateChangeListener() {
                    @Override
                    public void onNavigationBarShow(int orientation, int height) {
                        topBar.setPadding(0, 0, height, 0);
                        bottomBar.setPadding(0, 0, height, 0);
                    }

                    @Override
                    public void onNavigationBarHide(int orientation) {
                        topBar.setPadding(0, 0, 0, 0);
                        bottomBar.setPadding(0, 0, 0, 0);
                    }
                });
        if (!ImagePickerTextRepository.INSTANCE.getHasChoose().isEmpty()) {
            hasChoose = ImagePickerTextRepository.INSTANCE.getHasChoose();
        } else {
            hasChoose = getString(R.string.hasChoose);
        }
        mSelectCount.setText(hasChoose + "（" + imagePicker.getSelectImageCount() + "）");
    }


    /**
     * 图片添加成功后，修改当前图片的选中数量
     * 当调用 addSelectedImageItem 或 deleteSelectedImageItem 都会触发当前回调
     */
    @Override
    public void onImageSelected(int position, ImageItem item, boolean isAdd) {
        String complete = "";
        if (!imagePicker.getCompleteText().isEmpty()) {
            complete = imagePicker.getCompleteText();
        } else if (!ImagePickerTextRepository.INSTANCE.getComplete().isEmpty()) {
            complete = ImagePickerTextRepository.INSTANCE.getComplete();
        } else {
            complete = getString(R.string.ip_complete);
        }
        if (imagePicker.getSelectImageCount() > 0) {
            mBtnOk.setText(String.format(complete + "%d/%d",
                    imagePicker.getSelectImageCount(), imagePicker.getSelectLimit()));
            mBtnOk.setEnabled(true);
            mBtnOk.setTextColor(ContextCompat.getColor(this, R.color.ip_text_primary_inverted));
        } else {
            mBtnOk.setText(complete);
            mBtnOk.setEnabled(false);
            mBtnOk.setTextColor(ContextCompat.getColor(this, R.color.ip_text_secondary_inverted));
        }
        mSelectCount.setText(hasChoose + "（" + imagePicker.getSelectImageCount() + "）");
        if (mCbOrigin.isChecked()) {
            long size = 0;
            for (ImageItem imageItem : selectedImages) {
                size += imageItem.size;
            }
            String fileSize = Formatter.formatFileSize(this, size);
            mCbOrigin.setText(getString(R.string.ip_origin_size, fileSize));
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_ok) {
            Intent intent = new Intent();
            intent.putExtra(ImagePicker.EXTRA_RESULT_ITEMS, imagePicker.getSelectedImages());
            setResult(ImagePicker.RESULT_CODE_ITEMS, intent);
            finish();
        } else if (id == R.id.btn_back) {
            Intent intent = new Intent();
            intent.putExtra(ImagePreviewActivity.ISORIGIN, isOrigin);
            setResult(ImagePicker.RESULT_CODE_BACK, intent);
            finish();
        }
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putExtra(ImagePreviewActivity.ISORIGIN, isOrigin);
        setResult(ImagePicker.RESULT_CODE_BACK, intent);
        finish();
        super.onBackPressed();
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        int id = buttonView.getId();
        if (id == R.id.cb_origin) {
            if (isChecked) {
                long size = 0;
                for (ImageItem item : selectedImages) {
                    size += item.size;
                }
                String fileSize = Formatter.formatFileSize(this, size);
                isOrigin = true;
                mCbOrigin.setText(getString(R.string.ip_origin_size, fileSize));
            } else {
                isOrigin = false;
                mCbOrigin.setText(getString(R.string.ip_origin));
            }
        }
    }

    @Override
    protected void onDestroy() {
        imagePicker.removeOnImageSelectedListener(this);
        super.onDestroy();
    }

    /**
     * 单击时，隐藏头和尾
     */
    @Override
    public void onImageSingleTap() {
        if (topBar.getVisibility() == View.VISIBLE) {
            topBar.setAnimation(AnimationUtils.loadAnimation(this, R.anim.top_out));
            bottomBar.setAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_out));
            topBar.setVisibility(View.GONE);
            bottomBar.setVisibility(View.GONE);
            tintManager.setStatusBarTintResource(Color.TRANSPARENT); //通知栏所需颜色
            //给最外层布局加上这个属性表示，Activity全屏显示，且状态栏被隐藏覆盖掉。
//            if (Build.VERSION.SDK_INT >= 16) content.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
        } else {
            topBar.setAnimation(AnimationUtils.loadAnimation(this, R.anim.top_in));
            bottomBar.setAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
            topBar.setVisibility(View.VISIBLE);
//            bottomBar.setVisibility(View.VISIBLE);
            tintManager.setStatusBarTintResource(R.color.ip_color_primary_dark); //通知栏所需颜色
            //Activity全屏显示，但状态栏不会被隐藏覆盖，状态栏依然可见，Activity顶端布局部分会被状态遮住
//            if (Build.VERSION.SDK_INT >= 16) content.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        }
    }
}
